﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace SlamCms.SharePoint.Core
{
	public class SharePointSiteCollection : SharePointAction<SharePointSiteCollection>
	{
		private SharePointApplication _application;
		
		public SharePointSiteCollection() :
			base()
		{
			_application = new SharePointApplication(SharePointItem);
		}

		public SharePointSiteCollection(SharePointItem baseItem)
		{
			SharePointItem = baseItem;
			_application = new SharePointApplication(SharePointItem);
		}

		public SharePointSite Site()
		{
			return Site(SPControl.GetContextWeb(HttpContext.Current).ID);
		}

		public SharePointSite Site(string siteName)
		{
			SharePointItem.SiteName = siteName;
			return new SharePointSite(SharePointItem);
		}

		public SharePointSite Site(Guid siteId)
		{
			SharePointItem.SiteId = siteId;
			return new SharePointSite(SharePointItem);
		}

		public void Site(Action<SPWeb> action)
		{
			if (SharePointItem.SiteId != Guid.Empty)
			{
				Site(SharePointItem.SiteId, action);
			}
			else if (!String.IsNullOrEmpty(SharePointItem.SiteName))
			{
				Site(SharePointItem.SiteName, action);
			}
			else
			{
				_application.SiteCollection(s =>
				{
					using (SPWeb web = s.OpenWeb())
					{
						action.Invoke(web);
					}
				});
			}
		}

		public void Site(Action<SPWeb, SPSite> action)
		{
			if (SharePointItem.SiteId != Guid.Empty)
			{
				Site(SharePointItem.SiteId, action);
			}
			else if (!String.IsNullOrEmpty(SharePointItem.SiteName))
			{
				Site(SharePointItem.SiteName, action);
			}
			else
			{
				_application.SiteCollection(sc =>
				{
					using (SPWeb s = sc.OpenWeb())
					{
						action.Invoke(s, sc);
					}
				});
			}
		}

		public void Site(string siteName, Action<SPWeb> action)
		{
			_application.SiteCollection(s =>
			{
				using (SPWeb web = s.AllWebs[siteName])
				{
					action.Invoke(web);
				}
			});
		}

		public void Site(string siteName, Action<SPWeb, SPSite> action)
		{
			_application.SiteCollection(sc =>
			{
				using (SPWeb s = sc.AllWebs[siteName])
				{
					action.Invoke(s, sc);
				}
			});
		}

		public void Site(Guid siteId, Action<SPWeb> action)
		{
			_application.SiteCollection(s =>
			{
				using (SPWeb web = s.AllWebs[siteId])
				{
					action.Invoke(web);
				}
			});
		}

		public void Site(Guid siteId, Action<SPWeb, SPSite> action)
		{
			_application.SiteCollection(sc =>
			{
				using (SPWeb s = sc.AllWebs[siteId])
				{
					action.Invoke(s, sc);
				}
			});
		}
	}
}
